package com.cjq.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cjq.domain.Admin;
import com.cjq.service.AdminService;
import com.cjq.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author junqiancai@foxmail.com
 * @since 2021/6/13 19:46
 */
@RestController
public class AdminController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PreAuthorize("hasRole('SUPER')")
    @GetMapping("/allAdmin")
    Result getAdmins(){
        final LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<Admin>();
        wrapper.select(Admin::getId,Admin::getUsername,Admin::getStatus)
                .eq(Admin::getRoleId,1);
        final List<Admin> list = adminService.list(wrapper);
        return Result.succeed(Result.SUCCESS,"查询成功",list);
    }

    @PreAuthorize("hasRole('SUPER')")
    @PostMapping("/admin")
    Result postAdmin(@RequestBody Admin admin){
        System.out.println(admin);
        //把密码加密后保存在数据库中
        admin.setRoleId(1)
                .setPassword(passwordEncoder.encode(admin.getPassword()));
        final boolean isSuccess = adminService.save(admin);
        if(isSuccess){
            return Result.succeed(Result.CREATE,"添加成功");
        }
        return Result.succeed(Result.Server_Error,"添加失败");
    }

    @PreAuthorize("hasRole('SUPER')")
    @GetMapping("/admin/forbid")
    Result forbidAdmin(@RequestParam("id") Integer id,@RequestParam("status")Integer status){
        LambdaUpdateWrapper<Admin> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Admin::getId, id).set(Admin::getStatus, status);
        final boolean update = adminService.update(lambdaUpdateWrapper);
        if(update)return Result.succeed(Result.SUCCESS,"操作成功");
        return Result.succeed(Result.Server_Error,"操作失败");
    }
}
